#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_errno.h"
#include "hi_pwm.h"
#include "hi_io.h"

static int g_beepState = 1;
#define     CLK_160M                160000000
#define     IOT_GPIO_IDX_2          2
#define     IOT_GPIO_IDX_8          8
#define     IOT_GPIO_PWM_FUNCTION   5
#define     IOT_PWM_PORT_PWM2       2
#define     IO_FUNC_GPIO_8_GPIO     0
#define     IOT_IO_PULL_UP          1

static void *PWMBeerTask(const char *arg)
{
    (void)arg;

    printf("PWMBeerTask start!\r\n");
    
    while (1) {
        if (g_beepState) {
            IoTPwmStart(IOT_PWM_PORT_PWM2, 50, 4000);
        } else {
            IoTPwmStop(IOT_PWM_PORT_PWM2);
        }
    }

    return NULL;
}

static void OnButtonPressed(char *arg)
{
    (void) arg;
    g_beepState = !g_beepState;
}

static void StartPWMBeerTask(void)
{
    osThreadAttr_t attr;


    IoTGpioInit(IOT_GPIO_IDX_2);
    hi_io_set_func(IOT_GPIO_IDX_2, IOT_GPIO_PWM_FUNCTION);
    IoTGpioSetDir(IOT_GPIO_IDX_2, IOT_GPIO_DIR_OUT);
    IoTPwmInit(IOT_PWM_PORT_PWM2);

    // hi_io_set_func(IOT_GPIO_IDX_8, IO_FUNC_GPIO_8_GPIO);
    // IoTGpioSetDir(IOT_GPIO_IDX_8, IOT_GPIO_DIR_IN);
    // hi_io_set_pull(IOT_GPIO_IDX_8, IOT_IO_PULL_UP);
    // IoTGpioRegisterIsrFunc(IOT_GPIO_IDX_8, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW,
    //     OnButtonPressed, NULL);

    IoTWatchDogDisable();

    attr.name = "PWMBeerTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)PWMBeerTask, NULL, &attr) == NULL) {
        printf("[StartPWMBeerTask] Falied to create PWMBeerTask!\n");
    }
}

APP_FEATURE_INIT(StartPWMBeerTask);